<html>
<head>

<title>Groovy Goodness: Groovy Mystic Expressions</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Groovy Mystic Expressions</h3>

<div class="post">
<p>With Groovy we can omit parenthesis in some cases, key-value parameters for a method are grouped into a group. If we combine all these features we can come up with some pretty mystic expressions. But it is also perfect for writing DSLs, because it doesn't look like real Java/Groovy code anymore. Here is a small sample of an expression that looks strange at first, but at a second look we can see the structure of method calls:</p>
<pre class="brush:groovy">
result = []

// Mystic expressions: (see assert for outcome)
say hello:world {
    'Groovy'
}
say hello:world { 
    'Java' 
}

assert "Say 'Hello Groovy world!'" == result[0]
assert "Say 'Hello Java world!'" == result[1]

// Actually we are invoking:
// say([hello: world({ 'Groovy' })])
// say([hello: world({ 'Java' })])
// We notice two methods: save(map) and world(closure).

// The methods:
def world(callable) {
    def result = callable()
    "Hello $result world!"
}

def say(map) {
    result &lt;&lt; "Say '${map.hello}'"
}
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>